package com.example.okhttp3;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class Register extends AppCompatActivity {
//    定义全局变量
    EditText mEtUserName,mEtPassWord,mEtRePassWord;
    Button mBtnRegister;
    private static final String TAG = "Register";
    String data;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
//      初始化控件
        initView();
//        事件处理
        initEvent();
    }

    private void initEvent() {
//        为mBtnRegister按钮添加点击事件
        mBtnRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                通过getText()方法获取编辑框中输入的值
                String username = String.valueOf(mEtUserName.getText());
                String password = String.valueOf(mEtPassWord.getText());
                String repassword = String.valueOf(mEtRePassWord.getText());

//                创建OkHttpClient对象
                OkHttpClient client = new OkHttpClient();
//                请求体
                RequestBody body = new FormBody.Builder()
                        .add("username", username)
                        .add("password", password)
                        .add("repassword", repassword)
                        .build();
//                通过Builder模式创建Request对象，必须有url参数
                final Request request = new Request.Builder()
                        .url("https://anli-wechat.boruiman.com/api/UserServer/user_register")
                        .post(body)
                        .build();
                final Call call = client.newCall(request);
                new Thread(() -> {
                    try {
                        Response request1 = call.execute();
                        data = request1.body().string();
                        Log.e(TAG,"run"+data);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }).start();
            }
        });
    }

    private void initView() {
//        绑定控件
        mEtUserName = findViewById(R.id.et_username);
        mEtPassWord = findViewById(R.id.et_password);
        mEtRePassWord = findViewById(R.id.et_repassword);
        mBtnRegister = findViewById(R.id.btn_register);
    }

}